package com.kizuki.lambda;

import org.junit.Test;
import org.springframework.core.convert.converter.Converter;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class TestLamda {

    @Test
    public void test(){

        // 断言
        Predicate<Integer> p = a -> a > 0;
        System.out.println(p.test(2));

        // 比较器
        Comparator<Integer> c = (a, b) -> b - a;

        // 映射<int, return>
        Function<Integer, String> f = a -> a + "";

        // 消费者 con可以写成con1
        // 方法归属者::方法名 静态方法的归属者为类名，普通方法归属者为对象
        Consumer<Integer> con = a -> { System.out.println(a); };
        Consumer<Integer> con1 = System.out::println;

        // 编译的时候会变成final
        Integer testCon = 1;
        // lambda表达式引用的是final
        Consumer<Integer> con2 = a -> System.out.println(testCon);
//        testCon += 2;
        System.out.println(testCon);

        // 生产者 s0可以写成是s1
        Supplier<List<Integer>> s0 = () -> new ArrayList<Integer>();
        Supplier<List<Integer>> s1 = ArrayList::new;

    }

    @Test
    public void test1(){ // 转换器
        Converter<Integer, String> converter = String::valueOf;
        String convert = converter.convert(12);
        System.out.println(convert.getClass());
    }


    private static int num = 0;
    @Test
    public void test2() throws InterruptedException {

        for (int i = 0; i < 10; i++) {
            int temp = i;
            new Thread(()->{
//                System.out.println(i); // 编译器会将局部变量用final修饰
                System.out.println(temp);
                num += temp;  // 实例字段和静态变量有读写权限
            }).start();
        }

        TimeUnit.SECONDS.sleep(1);
        System.out.println(num);
    }

    /**
     * :: 运算符
     * object::instanceMethod 等价于 (...) -> {object.instanceMethod(...)}  // System.out::println
     * Class::staticMethod    等价于 (...) -> {Class.staticMethod(...)}     // String::valueOf
     * Class::instanceMethod  等价于 (a, ...) -> {a.instanceMethod(...)}    // Optional.ofNullable(user).map(User::getName)
     * Class::new             等价于 (...) -> {new Class(...)}              // Integer::new
     */

}
